package com.gzhryc.shared_device.oem.h5.mng.controllers.config;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.poi.ss.usermodel.Workbook;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.SelectResult;
import com.gzhryc.common.excel.ExcelTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentFuncModel;
import com.gzhryc.shared_device.oem.code.agent.dao.models.FuncModelCount;
import com.gzhryc.shared_device.oem.code.agent.services.AgentFuncModelService;
import com.gzhryc.shared_device.oem.code.config.dao.db.FuncModel;
import com.gzhryc.shared_device.oem.code.config.dao.enums.FuncModelEnum;
import com.gzhryc.shared_device.oem.code.config.services.FuncModelService;
import com.gzhryc.shared_device.oem.code.config.services.dto.FuncModelSearch;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;

public class FuncModelController {

    @Route(value = { "/config/func_model/list.html" })
    public String list(HttpServletRequest request) {
        request.setAttribute("typeList", FuncModelEnum.Type.values());
        request.setAttribute("stateList", FuncModelEnum.State.values());
        return "/config/func_model/list.html";
    }

    @Route(value = "/config/func_model/list.data")
    public ListResult<FuncModel> listData(HttpServletRequest request) {
        ListResult<FuncModel> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        FuncModelSearch search = WebUtils.getParameter(request,FuncModelSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(FuncModelService.self().countBySearch(search));
        List<FuncModel> funcModelList = FuncModelService.self().findBySearch(search,pageNo,pageLimit);
        if(funcModelList != null && funcModelList.size() > 0){
            List<Long> funcModelIds = new ArrayList<>();
            for(FuncModel funcModel : funcModelList){
                funcModelIds.add(funcModel.getId());
            }

            List<FuncModelCount> agentCountList = AgentFuncModelService.self().findCountByFuncModelIds(funcModelIds);

            String resDomain = WebConstants.getResDomain(request);
            for(FuncModel funcModel : funcModelList){
                if(StringTools.isNotBlank(funcModel.getIconUrl())) {
                    funcModel.setIconUrl(resDomain + funcModel.getIconUrl());
                }
                funcModel.setAgentUseCount(0L);
                if(agentCountList != null && agentCountList.size() > 0) {
                    for(FuncModelCount agentCount : agentCountList) {
                        if (funcModel.getId().equals(agentCount.getFuncModelId())){
                            funcModel.setAgentUseCount(agentCount.getUseCount());
                            break;
                        }
                    }
                }
            }
            result.setCode(DtoConstants.SUCCESS,null);
            result.getBody().setData(funcModelList);
        }
        return result;
    }

    @Route(value = { "/config/func_model/add.html" })
    public String add(HttpServletRequest request) {
    	request.setAttribute("typeList", FuncModelEnum.Type.values());
        request.setAttribute("stateList", FuncModelEnum.State.values());
        if(WebConstants.isLocalRes()) {
        	return "/config/func_model/edit2.html";
        }
        return "/config/func_model/edit.html";
    }

    @Route(value = {"/config/func_model/add.do"})
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增失败，请稍后再试");
        FuncModel funcModel = WebUtils.getParameter(request,FuncModel.class);
        try {
			if(FuncModelService.self().add(funcModel)){
			    result.setCode(DtoConstants.SUCCESS,null);
			}
		} catch (LogicException e) {
			result.setMsg(e.getMessage());
		}
        return result;
    }

    @Route(value = { "/config/func_model/update.html" })
    public String update(HttpServletRequest request) {
        Long id = WebUtils.getLong(request,"id");
        FuncModel funcModel = FuncModelService.self().getById(id);
        WebUtils.setAttribute(request,funcModel);
        request.setAttribute("typeList", FuncModelEnum.Type.values());
        request.setAttribute("stateList", FuncModelEnum.State.values());
        if(WebConstants.isLocalRes()) {
        	return "/config/func_model/edit2.html";
        }
        return "/config/func_model/edit.html";
    }

    @Route(value = {"/config/func_model/update.do"})
    public AjaxResult doUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败，请稍后再试");
        FuncModel funcModel = WebUtils.getParameter(request,FuncModel.class);
        try {
			if(FuncModelService.self().updateNotNull(funcModel)){
			    result.setCode(DtoConstants.SUCCESS,null);
			}
		} catch (LogicException e) {
			result.setMsg(e.getMessage());
		}
        return result;
    }

    @Route(value = {"/config/func_model/del.do"})
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除失败，请稍后再试");
        Long id = WebUtils.getLong(request,"id");
        if(FuncModelService.self().deleteById(id)){
            result.setCode(DtoConstants.SUCCESS,null);
        }
        return result;
    }

    @Route("/config/func_model/select.data")
    public SelectResult selectData(HttpServletRequest request) {
        SelectResult result = new SelectResult(DtoConstants.SUCCESS);
        String term = request.getParameter("term");
        Integer type = WebUtils.getInteger(request,"type");
        Long userId = WebUtils.getLong(request,"userId");
        Integer state = WebUtils.getInteger(request,"state",FuncModelEnum.State.Choose.index());
        Integer page = WebUtils.getInteger(request, "page", 1);

        FuncModelSearch search = new FuncModelSearch();
        search.setName(term);
        search.setType(type);
        if(state != 0) {
            search.setState(state);
        }
        Long total = 0L;
        List<FuncModel> list = FuncModelService.self().findBySearch(search, page, WebConstants.PAGE_LIMIT);
        if (list != null) {
            List<AgentFuncModel> agentFuncModelList = null;
            if(userId != null){
                agentFuncModelList = AgentFuncModelService.self().findJoinByUserId(userId);
            }

            for (FuncModel funcModel : list) {
                boolean flag = true;
                if(agentFuncModelList != null && agentFuncModelList.size() > 0){
                    for(AgentFuncModel agentFuncModel : agentFuncModelList){
                        if(agentFuncModel.getFuncModelId().equals(funcModel.getId())){
                            flag = false;
                            break;
                        }
                    }
                }
                if(flag) {
                    SelectResult.Item item = new SelectResult.Item();
                    item.setId(funcModel.getId().toString());
                    item.setText(funcModel.getName() + "("+funcModel.getTypeName()+") - " + funcModel.getStateName());
                    result.getBody().getData().add(item);
                }
            }
            total += list.size();
        }
        result.getBody().setPage(page);
        result.getBody().setLimit(WebConstants.PAGE_LIMIT);
        result.getBody().setTotal(total);
        return result;
    }

    /**
	 * 导出
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@Route(value = "/config/func_model/exportExcel.html")
	public void doExportToExcel(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {
		FuncModelSearch search = WebUtils.getParameter(request,FuncModelSearch.class);
		String[] titles = {"类型","功能模块名","功能模块图标","功能模块路径","描述","状态"};
		List<Object[]> data = new ArrayList<>();
		List<FuncModel> dataList = FuncModelService.self().findBySearch(search, null, null);
		if(dataList != null) {
			for (FuncModel entity : dataList) {
				Object[] objects = new Object[6];
				objects[5] = entity.getState(); 
				objects[4] = entity.getNote();
				objects[3] = entity.getUrl();
				objects[2] = entity.getIconUrl();
				objects[1] = entity.getName();
				objects[0] = entity.getType();
				data.add(objects);
			}
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String name = format.format(new Date());
		WebUtils.exportExcel(response, name);
		ExcelTools.export(response.getOutputStream(), "功能模块信息", null, titles, data);
	}
	
	//导入
	@Route(value = "/config/func_model/uploadExcel.do")
	public AjaxResult uploadExcel(HttpServletRequest request, FileItem file,HttpSession session) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "导入失败，请稍后再试！");
		try {
			Workbook workbook = ExcelTools.readExcelToWorkbook(file.getName(), file.getInputStream());
			List<FuncModel> data = ExcelTools.readExcel(workbook, FuncModel.class,
					new String[] { "type","name","iconUrl","url","note","state"},
					0, 1);
			int i = 0;
			if (data != null && data.size() > 0) {
				//记录插入失败的记录
				List<FuncModel> failList = new ArrayList<FuncModel>();
				for (FuncModel funcModel : data) {
					if(FuncModelService.self().add(funcModel)) {
						i++;
					}else {
						failList.add(funcModel);
					}
				}
			}
			if (i > 0) {
				result.setCode(DtoConstants.SUCCESS, "成功导入"+i+"条记录");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
